/*
 * $Id: LogEventQuery.java 17 2014-08-28 10:52:50Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws6.system.view;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.omnifaces.cdi.ViewScoped;
import org.omnifaces.util.Messages;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import cn.ratking.demo.jaws6.model.LogEvent;
import cn.ratking.demo.jaws6.system.service.LogEventService;
import cn.ratking.demo.jaws6.system.vo.LogEventSearchCriteria;

/**
 * 日志事件查询、删除
 */
@Named
@ViewScoped
public class LogEventQuery implements Serializable {

    /** 系统日志 */
    @Inject
    private transient Logger log;
    @Inject
    private LogEventService logEventService;
    /** 事件源 */
    @Inject
    private Event<LogEvent> logEventSrc;
    /** 页面查询条件 */
    @Inject
    private LogEventSearchCriteria searchCriteria;
    /** 结果列表 */
    private LazyDataModel<LogEvent> resultModel;
    /** 选择的日志 */
    private LogEvent[] selectedLogEvents;

    public LogEvent[] getSelectedLogEvents() {
        return selectedLogEvents;
    }

    public void setSelectedLogEvents(LogEvent[] selectedLogEvents) {
        this.selectedLogEvents = selectedLogEvents;
    }

    /**
     * 获得结果列表
     *
     * @return
     */
    public LazyDataModel<LogEvent> getResultModel() {
        if (resultModel == null) {
//            // @see http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/
//            if (!FacesContext.getCurrentInstance().getRenderResponse()) {
//                log.debug("Debug: 优化：PersonQuery.getResultModel(), return null, currentPhaseId=" + FacesContext.getCurrentInstance().getCurrentPhaseId());
//                // Until we are rendering the page, we don’t really need our data so we only load it if this method returns true.
//                return null;
//            }

            resultModel = new LazyDataModel<LogEvent>() {
                @Override
                public List<LogEvent> load(int first, int pageSize,
                        String sortField, SortOrder sortOrder,
                        Map<String, Object> filters) {
                    int rowCount = this.getRowCount();
                    if (rowCount == 0) {
                        return new ArrayList<LogEvent>(0);
                    }
                    if (first >= rowCount) {
                        // 当查询使用的首记录超出记录总数时，调整首记录
                        if (rowCount % pageSize == 0) {
                            first = ((rowCount / pageSize) - 1) * pageSize;
                        } else {
                            first = (rowCount / pageSize) * pageSize;
                        }
                    }
                    return logEventService.getResultList(first, pageSize,
                            sortField, sortOrder, searchCriteria);
                }

                @Override
                public LogEvent getRowData(String rowKey) {
                    return (LogEvent) logEventService.findById(Long.valueOf(rowKey));
                }

                @Override
                public Object getRowKey(LogEvent object) {
                    return object.getLogEventId().toString();
                }
            };
            resultModel.setRowCount(logEventService.getRowCount(searchCriteria));
//            // Arbitrary value only for test purposes.
//            // @see http://forum.primefaces.org/viewtopic.php?f=3&t=4956
            resultModel.setPageSize(20);
        }
        return resultModel;
    }

    public void deleteById(Long logEventId) {
        logEventService.deleteById(logEventId);
        String msg = "删除日志事件[" + logEventId + "]成功";
        log.debug(msg);
        Messages.addGlobalInfo(msg);
        logEventSrc.fire(new LogEvent(msg));

        refresh();
    }

    public void batchDelete() {
//        log.debug("开始调用 batchDelete()批量删除日志, selectedLogEvents="
//                + selectedLogEvents);
        if (selectedLogEvents == null || selectedLogEvents.length == 0) {
            String msg = "批量删除日志时没有选择日志";
            log.warn(msg);
            Messages.addGlobalWarn(msg);
            return;
        }

        List<Long> logEventIdList = new ArrayList<Long>(selectedLogEvents.length);
        for (LogEvent tmpLogEvent : selectedLogEvents) {
            logEventIdList.add(tmpLogEvent.getLogEventId());
        }
        logEventService.batchDelete(logEventIdList);
        String msg = "批量删除日志事件成功";
        log.debug(msg);
        Messages.addGlobalInfo(msg);
        logEventSrc.fire(new LogEvent(msg));

        refresh();
    }

    /** 查询 */
    public void search() {
        refresh();
    }

    /** 刷新 */
    private void refresh() {
        resultModel = null;
        selectedLogEvents = null;
    }
}
